package com.example.sunsg.okhttptest.service;

import android.app.Service;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.util.Log;

import com.example.sunsg.okhttptest.IMyAidlInterface;
import com.example.sunsg.okhttptest.IMyAidlInterfaceAddBook;
import com.example.sunsg.okhttptest.IMyAidlInterfaceAddBookCallBack;
import com.example.sunsg.okhttptest.IMyAidlInterfaceCallBack;
import com.example.sunsg.okhttptest.bean.Book;
import com.example.sunsg.okhttptest.bean.Data;
import com.example.sunsg.okhttptest.bean.User;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;

public class ProcessSercice extends Service {

    private Messenger mReplayMessager;//activity返回的messenger 用于向activity发送数据
    private Messenger mMessenger;//返回给activity的Messenger 用于接收activity发送的数据
    private MyHandler mHandler;
    private AtomicBoolean mIsServeiceDestory = new AtomicBoolean(false);
    public ProcessSercice() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mHandler = new MyHandler(this);
        mMessenger = new Messenger(mHandler);
        list.add(new Book("uu",22));
        list.add(new Book("tt",33));
        mHandler.sendEmptyMessageDelayed(1,5000);
    }

    @Override
    public void onDestroy() {
        mIsServeiceDestory.set(true);
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {

//        return mMessenger.getBinder();
//        return binder;
          return bindAddBook;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i("test","onunbind");
        return super.onUnbind(intent);
    }

    public AtomicBoolean isServieceDestory(){
        return mIsServeiceDestory;
    }


    //======================== messenger=========================================
    class MyHandler extends Handler{
        private final WeakReference<ProcessSercice> mSeivice;
        public MyHandler(ProcessSercice sercice){
            mSeivice = new WeakReference<ProcessSercice>(sercice);
        }
        @Override
        public void handleMessage(Message msg) {
            if(mSeivice.get() != null){
                if(msg.what == 0){//messenger
                    Bundle bundle = msg.getData();
                    if(bundle != null){
                        bundle.containsKey("data");
                        Log.i("test","serveie return data = "+(bundle.getString("data")));
                    }
//                    Log.i("test","activity send data = "+(msg.obj).toString());
                    mReplayMessager = msg.replyTo;
                    new MyThread().start();
                }else if(msg.what == 1){//addBook
                    if(list.size() >= maxBookCount){
                        mHandler.removeMessages(1);
                    }else{
                        Book book = new Book("book",list.size());
                        onBookArrive(book);
                        mHandler.sendEmptyMessageDelayed(1,1500);
                    }
                }
            }
        }
    }

    class MyThread extends Thread {
        public void run() {
            System.out.println("Thread start");
            try {
                Thread.sleep(5 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Message msg = Message.obtain(null, 0);
            Bundle bundle = new Bundle();
            bundle.putString("data","servece susng");
            msg.setData(bundle);
            try {
                mReplayMessager.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }


    //======================== IMyAidlInterface =========================================

    final RemoteCallbackList<IMyAidlInterfaceCallBack> calls = new RemoteCallbackList<IMyAidlInterfaceCallBack>();

    private final IMyAidlInterface.Stub binder = new IMyAidlInterface.Stub(){

        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {

        }

        @Override
        public User getUser() throws RemoteException {
            User user = new User("11","susng");
            return user;
        }

        @Override
        public void register(IMyAidlInterfaceCallBack callback) throws RemoteException {
            calls.register(callback);
        }

        @Override
        public void unRegister(IMyAidlInterfaceCallBack callback) throws RemoteException {
            calls.unregister(callback);
        }
    };

    //================================================ IMyAidlInterfaceAddBook =====================

    private RemoteCallbackList<IMyAidlInterfaceAddBookCallBack> callBackAddBook = new RemoteCallbackList<>();
    private CopyOnWriteArrayList<Book> list = new CopyOnWriteArrayList<Book>();//写慢 度快
    private List<Book> lists = Collections.synchronizedList(new ArrayList<Book>());//读快 写慢
    private final int maxBookCount = 10;
    private IMyAidlInterfaceAddBook.Stub bindAddBook = new IMyAidlInterfaceAddBook.Stub(){

        @Override
        public void addBook(Book book) throws RemoteException {
            list.add(book);
        }

        @Override
        public List<Book> getBooks() throws RemoteException {
            return list;
        }

        @Override
        public void registerLintener(IMyAidlInterfaceAddBookCallBack callBack) throws RemoteException {
            callBackAddBook.register(callBack);
        }

        @Override
        public void unregisterListener(IMyAidlInterfaceAddBookCallBack callBack) throws RemoteException {
            callBackAddBook.unregister(callBack);
        }
    };

    private void onBookArrive(Book book){
        list.add(book);
        final int size = callBackAddBook.beginBroadcast();
        for (int i = 0;i<size;i++){
            IMyAidlInterfaceAddBookCallBack call = callBackAddBook.getBroadcastItem(i);
            if(call != null){
                try {
                    call.onNewBookArrice(book);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }
        callBackAddBook.finishBroadcast();

    }
}
